<template>
  <div>TestBpmn camunda</div>
  <div>
    <div style="display: flex; justify-content: flex-end">
      <el-button @click="downloadXML" type="primary">下载</el-button>
    </div>
    <div class="containers" style="display: flex; width: 100%; height: 96vh">
      <div class="canvas" style="width: 100%" id="canvas"></div>
      <div id="properties"></div>
    </div>
  </div>
</template>
<script setup lang="ts" name="TestBpmn1">
import "bpmn-js/dist/assets/diagram-js.css"; // 左边工具栏以及编辑节点的样式
import "bpmn-js/dist/assets/bpmn-font/css/bpmn.css";
import "bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css";
import "bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css";

import "@bpmn-io/properties-panel/assets/properties-panel.css"; // 右边工具栏样式

import BpmnModeler from "bpmn-js/lib/Modeler";

// 右侧边栏属性
import {
  BpmnPropertiesPanelModule, //右侧属性栏这个框
  BpmnPropertiesProviderModule, //右侧属性栏里的内容
  ZeebePropertiesProviderModule // Camunda 8 provider
} from "bpmn-js-properties-panel";

// Camunda 8 behaviors
import ZeebeBehaviorsModule from "camunda-bpmn-js-behaviors/lib/camunda-cloud";

// Camunda 8 moddle extension
import zeebeModdle from "zeebe-bpmn-moddle/resources/zeebe.json";

let bpmnModeler: any = null;

const initBpmnModeler = () => {
  if (bpmnModeler) return;
  let data = document.getElementById("bpmnCanvas");
  console.log(data, "data");

  bpmnModeler = new BpmnModeler({
    container: "#canvas",
    propertiesPanel: {
      parent: "#properties"
    },
    keyboard: { bindTo: document }, // 使用键盘快捷键
    // 添加到扩展模块内
    additionalModules: [
      BpmnPropertiesPanelModule,
      BpmnPropertiesProviderModule,
      ZeebePropertiesProviderModule,
      ZeebeBehaviorsModule
    ],
    moddleExtensions: {
      zeebe: zeebeModdle
    }
  });
  bpmnModeler.createDiagram();
};
const downloadXML = () => {
  bpmnModeler.saveXML({ format: true }, (err, xml) => {
    if (!err) {
      console.log(xml);
      // 获取文件名
      const name = getFileName(xml);
      // 把输就转换为URI，下载要用到的
      const encodedData = encodeURIComponent(xml);
      const downloadLink = document.createElement("a");
      if (xml) {
        // 将数据给到链接
        downloadLink.href = "data:application/bpmn20-xml;charset=UTF-8," + encodedData;
        // 设置文件名
        downloadLink.download = name;
        // 触发点击事件开始下载
        downloadLink.click();
      }
    }
  });
};
const getFileName = xml => {
  let split = xml.split('process id="');
  return split[1].split('" ')[0] + ".bpmn20.xml";
};

onMounted(() => {
  initBpmnModeler();
  console.log(bpmnModeler);
});
</script>

<style scoped></style>
